
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Iterator;

import model.CItem;
import model.CItemList;


/*
 * Example1.java
 *
 * Created on August 28, 2001, 12:37 PM
 */


/**
 *  A simple example of storing data in a collection class (ArrayList) and 
 *    then place this data into persistence storage. The example continues 
 *    by reading the stored data and writing it back to the screen. This example 
 *    is best understood by referencing the jdk documentation for all 
 *    classes that you have not encountered before. 
 */


public class Example1 {

    public static void main(String args[])
    {
	CItemList aListofItems = new CItemList();			// constructs empty CList of oneItemtems
        CItem oneItem; 

	int num, i;

	for (i = 0; i < 10; i++)
	{
		num = i;
		oneItem = new CItem(num," string associated with item " + i);
		aListofItems.addItem(oneItem);
	}

        /* We are writing to the default directory because I 
         *  do not know your directory structure. If you wanted to 
         *  write to a specific directory, use Unix slashes : 
         * FileOutputStream fos = new FileOutputStream("c:/bruce/test.ser");
         */

	   try {
	       FileOutputStream fos = new FileOutputStream("test.ser");
	       ObjectOutputStream oos = new ObjectOutputStream(fos);
	       oos.writeObject(aListofItems);
	       oos.close();
	   }
	   catch (FileNotFoundException e) {
	    System.err.println("Could not find test.ser " + e);   	
	   }
	   catch (IOException e) {
	    System.err.println("Some Error writing to stream " + e);   	
	   }
	   catch (Exception e){
	        System.err.println(e);
	    }	

	   aListofItems.removeAll();

//	 Display the list to the screen

	        
	    try {
	        FileInputStream fis = new FileInputStream("test.ser");
	        ObjectInputStream ois = new ObjectInputStream(fis);
	        aListofItems = (CItemList) ois.readObject();
	        ois.close();
	    }
	    catch (FileNotFoundException e) {
	        System.err.println("Could not find test.ser " + e);   	
	    }
	    catch (IOException e) {
	        System.err.println("Some Error writing to stream " + e);   	
	    }
	    catch (Exception e){
	            System.err.println(e);
	    }	
	                      
	     if (aListofItems != null) {
	        System.out.println("Contents of the list are:");
	        Iterator<CItem> iter = aListofItems.iterator();
	        while (iter.hasNext()) {
	            oneItem = iter.next();
	            Integer datastr = oneItem.getMyInteger();
	            System.out.println(datastr.toString() + " " + oneItem.getMyString());
	        }
	     }                         
  }
}
